package cn.usts.edu.lesson03;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class TcpFileClientDemo {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
            OutputStream outputStream = socket.getOutputStream();
            // 读取文件
            FileInputStream fileInputStream = new FileInputStream("D:\\all_projects\\java_projects\\java_ij\\springMVC\\NetWork\\src\\cn\\usts\\edu\\lesson03\\hello.txt");
            //FileInputStream fileInputStream = new FileInputStream(new File("D:\\all_projects\\java_projects\\java_ij\\springMVC\\NetWork\\src\\cn\\usts\\edu\\lesson03\\hello.txt"));
            // 写出文件
            byte[] buffer=new byte[1024];
            int len;
            while ((len=fileInputStream.read(buffer))!=-1){
                outputStream.write(buffer,0,len);
            }

            // 如果没有这句,客户端又进入了等待接收的状态,可是服务器那边没有断开文件的连接,没有办法发送东西过来,所以要先切断输出流
            socket.shutdownOutput();

            // 服务器告诉客户端的话"文件接收完毕"
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            InputStream inputStream = socket.getInputStream();
            int len2;
            byte[] buffer2=new byte[1024];
            while ((len2=inputStream.read(buffer2))!=-1){
                byteArrayOutputStream.write(buffer2,0,len2);
            }
            System.out.println(byteArrayOutputStream.toString());

            //关闭
            byteArrayOutputStream.close();
            outputStream.close();
            fileInputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
